package com.cloudpivot.receivales.ding.robot.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkdoc_1_0.models.GetRelatedWorkspacesHeaders;
import com.aliyun.dingtalkdoc_1_0.models.GetRelatedWorkspacesRequest;
import com.aliyun.dingtalkdoc_1_0.models.GetRelatedWorkspacesResponse;
import com.aliyun.teaopenapi.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.cloudpivot.receivales.ding.basic.service.DingBasicService;
import com.cloudpivot.receivales.ding.basic.service.impl.HttpAPIServiceForDing;
import com.cloudpivot.receivales.ding.userinfo.service.DingUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 知识库相关服务
 */
@Service
@Slf4j
public class DocSpaceServiceImpl {

    @Autowired
    private DingBasicService dingBasicService;

    @Autowired
    private DingUserService dingUserService;

    @Autowired
    private HttpAPIServiceForDing httpAPIServiceForDing;

    //知识库id(系统运维部)
    private String WORKSPACE="oJRz0nk6ZnbpmLZM";

    public Map<String,String> filemaps=null;


    /**
     * 搜索知识库中符合要求 文档信息
     * key=知识名称 value=url
     *
     */
    public Map<String,String> searchFileName(String nameKey) {

        if(Objects.isNull(filemaps)){
            return null;
        }

        Map<String, String> retMap = new HashMap<>();
        for (Map.Entry<String, String> _m : filemaps.entrySet()) {
            if (_m.getKey().toLowerCase().contains(nameKey.toLowerCase())) {

                retMap.put(_m.getKey(), _m.getValue());
            }
        }

        return retMap;

    }

    /**
     * 获取全部的 知识库 文档
     * @param uid
     */
//    private void getAllFile() {
//        Map<String, String> _map = new HashMap<>();
//        String unionId = dingUserService.dingUidToUnionId("020722623423157211");
//        getAllFileIteration(unionId, "", _map);
//        this.filemaps = _map;
////        log.info("文件结果Map:{}", JSONObject.toJSONString(_map));
//    }

    /**
     * 获取目录结构 含子目录结构
     * 系统运维部的知识库 workspaceid = oJRz0nk6ZnbpmLZM
     * 方法 入参函token
     */
    public void getAllFileIteration(String unionId,String dentryId,Map<String,String> fileMap,String access_token) {

        Map<String, Object> map = new HashMap<>();
        map.put("operatorId", unionId);
        map.put("maxResults", 500);
        if(StringUtils.isNotBlank(dentryId)){
            map.put("dentryId", dentryId);
        }
        String reqUrl = String.format("https://api.dingtalk.com/v2.0/doc/spaces/%s/directories",WORKSPACE);
//        String access_token = dingBasicService.getToken("dinggroup");
        try {
            String ret = httpAPIServiceForDing.doGetDingParam(reqUrl, map, access_token);
            //获取结果
            JSONObject retJson = JSONObject.parseObject(ret);
            JSONArray childrenJson = retJson.getJSONArray("children");
            for (Object obj : childrenJson) {
                JSONObject child = (JSONObject) obj;
                boolean hasChildren = child.getBoolean("hasChildren");
                String dentryType = child.getString("dentryType");
                String childrenDentryId = child.getString("dentryId");
                String name = child.getString("name");
                String url = child.getString("url");

                if (hasChildren && dentryType.equals("folder")) {
                    if(directorCheck(name)){
                        continue;
                    }
                    //迭代取值
                    getAllFileIteration(unionId, childrenDentryId, fileMap, access_token);
                }else{
                    //赋值map
                    fileMap.put(name, url);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error---->"+e);
        }
    }

    /**
     * 去除的 目录
     * @param s
     * @return
     */
    private boolean directorCheck(String s) {
        if (s.equals("知识海报") || s.equals("知识库快速使用手册")) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取目录结构 含子目录结构
     * 系统运维部的知识库 workspaceid = oJRz0nk6ZnbpmLZM
     */
    public void getDirectories(String uid,String dentryId) {
        String operatorId = dingUserService.dingUidToUnionId(uid);
        Map<String, Object> map = new HashMap<>();
        map.put("operatorId", operatorId);
        map.put("maxResults", 500);
        map.put("dentryId", "oJRz0yB3LQ8QwXLZ");
        String url = String.format("https://api.dingtalk.com/v2.0/doc/spaces/%s/directories",WORKSPACE);
        String access_token = dingBasicService.getToken("dinggroup");

        try {
            String ret = httpAPIServiceForDing.doGetDingParam(url, map, access_token);
            log.info("ret---->{}", ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取知识库节点信息 基本用不到
     * @param unionId
     * @param dentryId
     */
    private void getDentries(String unionId,String dentryId) {
        String url="https://api.dingtalk.com/v2.0/doc/spaces/oJRz0nk6ZnbpmLZM/dentries/"+dentryId+"?operatorId="+unionId+"&includeSpace=false";
        String access_token = dingBasicService.getToken("dinggroup");

        try {
            String ret=httpAPIServiceForDing.doGetDing(url, access_token);
            log.info("ret---->{}", ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
